package com.example.randox;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.randox.MemberActivity.MyCount;

import library.DatabaseHandler;
import library.UserFunctions;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ChatActivity extends Activity {
	
	private DatabaseHandler db;
	private HashMap<String, String> userDetails;
	private UserFunctions userFunction;
	
	private TextView name;
	private ImageView close;
	private EditText message; 
	private TextView send;
	
	private ListView listMessages;
	private ArrayAdapter<String> listAdapter ;
	
	private static String KEY_SUCCESS = "success";
	private static String KEY_FIRSTNAME = "firstname";
	private static String KEY_LASTNAME  = "lastname";
	private static String KEY_CONVERSATION  = "idConversation";
	
	private Handler handler;

	private String lastMessage;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_chat);

		db = new DatabaseHandler(getApplicationContext());
        userDetails = db.getUserDetails();
        
    	userFunction = new UserFunctions();
    	
		name = (TextView)findViewById(R.id.textView1);
		close = (ImageView)findViewById(R.id.imageView1);
		send = (TextView)findViewById(R.id.button1);
		message = (EditText)findViewById(R.id.editText1);
		listMessages = (ListView)findViewById(R.id.list);
		
		handler = new Handler();
		
		JSONObject json = userFunction.infosUser(userDetails.get("email").toString());
        try {
        	
            if (json.getString(KEY_SUCCESS) != null) {
                String res = json.getString(KEY_SUCCESS); 
                if(Integer.parseInt(res) == 1){
                    JSONObject json_user = json.getJSONObject("user");
                    name.setText(json_user.getString(KEY_FIRSTNAME).toString()+" "+json_user.getString(KEY_LASTNAME).toString());
                    KEY_CONVERSATION=json_user.getString(KEY_CONVERSATION).toString();
                    KEY_FIRSTNAME=json_user.getString(KEY_FIRSTNAME).toString();
                    KEY_LASTNAME=json_user.getString(KEY_LASTNAME).toString();
                }else{
                	 Toast.makeText(ChatActivity.this, " ", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
        
        
		close.setOnClickListener(new View.OnClickListener() {
		    public void onClick(View v) {
		    	AlertDialog.Builder alertDialog = new AlertDialog.Builder(ChatActivity.this);
		    	alertDialog.setTitle("Break the link ?");
		    	alertDialog.setMessage("Break the link between you and "+KEY_FIRSTNAME+" "+KEY_LASTNAME +" ?");
		    	alertDialog.setIcon(R.drawable.ic_alert);
		    	alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		                public void onClick(DialogInterface dialog, int which) {
		                	KEY_CONVERSATION="idConversation";
		                	 KEY_FIRSTNAME = "firstname";
		                	 KEY_LASTNAME = "lastname";
		                		JSONObject json = userFunction.closeConversation(userDetails.get("email").toString());
		                        try {
		                            if (json.getString(KEY_SUCCESS) != null) {
		                                String res = json.getString(KEY_SUCCESS); 
		                                if(Integer.parseInt(res) == 1){
			       		                	 Intent i = new Intent(ChatActivity.this, MemberActivity.class);
			                                 i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			                                 startActivity(i);
			                                 finish();
		                                }else{
		                                	 Toast.makeText(ChatActivity.this, " ", Toast.LENGTH_SHORT).show();
		                                }
		                            }
		                        } catch (JSONException e) {
		                            e.printStackTrace();
		                        }
		                }
		        });
		    	alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) {
	                
	                }
	        });
		    	alertDialog.show();
		    	
		    }
		});
		
		
		
		send.setOnClickListener(new View.OnClickListener() {
		    public void onClick(View v) {
		    	
		    	if(!message.getText().toString().matches("") && !message.getText().toString().matches(" ")){
				    	JSONObject json = userFunction.sendMessage(Integer.parseInt(userDetails.get("idUser").toString()),Integer.parseInt(KEY_CONVERSATION),message.getText().toString());
				        try {
				        	
				            if (json.getString(KEY_SUCCESS) != null) {
				                String res = json.getString(KEY_SUCCESS); 
				                if(Integer.parseInt(res) == 1){
				                	message.setText("");
				                }else{
				                	 
				                }
				            }
				        } catch (JSONException e) {
				            e.printStackTrace();
				        }
		    	}else{
		    		 Toast.makeText(ChatActivity.this, "Please enter a message", Toast.LENGTH_SHORT).show();
		    	}
		    }
		});
		
		
		final ArrayList<String> list = new ArrayList<String>();
		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
		lastMessage="";
		
		final Runnable r = new Runnable()
		{
		    public void run() 
		    {
		    	
		    	JSONObject json = userFunction.printMessage(Integer.parseInt(KEY_CONVERSATION));
		        try {
		        	
		            if (json.getString(KEY_SUCCESS) != null) {
		                String res = json.getString(KEY_SUCCESS); 
		                if(Integer.parseInt(res) == 1){
		                	JSONObject json_user = json.getJSONObject("user");
		                	
		                	if(!lastMessage.toString().equals(json_user.getString("message_body"))){
		                		list.add(json_user.getString("firstname")+" : "+json_user.getString("message_body"));
		                	}
		                	
		                	lastMessage=json_user.getString("message_body");
					    	adapter.notifyDataSetChanged();
					    	listMessages.setAdapter(adapter);
		                }else{
		                	 
		                }
		            }
		        } catch (JSONException e) {
		            e.printStackTrace();
		        }
		    	
		    	
		    	
		    	handler.postDelayed(this, 3000);
		    }
		};

		handler.postDelayed(r, 3000);
		
		

	}

	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.logout:
			userFunction.logoutUser(getApplicationContext());
            Intent login = new Intent(getApplicationContext(), LoginActivity.class);
            login.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(login);
            finish();
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	
	  @Override
	    public void onBackPressed() {
		  finish();
          System.exit(0);
	 }

}
